package com.dk.util.datacheck;

import com.dk.domain.ApiEntity;
import com.dk.exception.ExcelDataException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Validator注解校验类
 */
public class ValidatorUtil {
    //获取Validator校验对象
    private static Validator validator = Validation.buildDefaultValidatorFactory()
            .getValidator();

    /**
     * 校验实体数据
     * @param obj 校验对象
     * @param <T> 泛型
     * @return
     */
    public static <T> Map<String,StringBuffer> validate(T obj){
        //异常数据
        Map<String,StringBuffer> errorMap = new HashMap<String,StringBuffer>();
        //校验实体数据将异常数据返回为set集合
        Set<ConstraintViolation<T>> set = validator.validate(obj,Default.class);
        //set集合不为空时,将异常数据塞到map
        if(set != null && set.size() >0 ){
            String property = null;
            for(ConstraintViolation<T> cv : set){
                //这里循环获取错误信息，可以自定义格式
                property = cv.getPropertyPath().toString();
                if(errorMap.get(property) != null){
                    errorMap.get(property).append("," + cv.getMessage());
                }else{
                    StringBuffer sb = new StringBuffer();
                    sb.append(cv.getMessage());
                    errorMap.put(property, sb);
                }
            }
        }
        return errorMap;
    }

    public static String getErrorMsg(Map<String,StringBuffer> errorMap){
        StringBuffer errorMsg = new StringBuffer();
        for(String key:errorMap.keySet()){
            errorMsg.append(errorMap.get(key).toString()+";\n") ;
        }
            return errorMsg.toString();
        }
}
